package cn.icare.cms.impl;

import cn.icare.cms.ListUtil;
import cn.icare.cms.ShopCartService;
import cn.icare.cms.StringUtil;
import cn.icare.cms.dao.mapper.CustomMapper;
import cn.icare.cms.dao.mapper.ShopCartMapper;
import cn.icare.cms.dao.po.Promotion;
import cn.icare.cms.dao.po.ShopCart;
import cn.icare.cms.model.ro.AddShopCartRO;
import cn.icare.cms.model.vo.rest.MsgDatasVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ShopCartServiceImpl implements ShopCartService {


    @Resource
    private ShopCartMapper shopCartMapper;
    @Resource
    private CustomMapper customMapper;

    private final Logger logger = LoggerFactory.getLogger(ShopCartServiceImpl.class);


    @Override
    public Long createOne(AddShopCartRO ro, Long memberId, BigDecimal price) {
        try {
            ShopCart model = new ShopCart();
            model.setMemberid(memberId);
            model.setImage(ro.getImage());
            model.setItemid(ro.getItemId());
            model.setTitle(ro.getTitle());
            model.setPrice(price);
            //   model.setPrice(ro.getPrice()); //商品价格需要重新计算
            model.setNum(ro.getNum());
            model.setCreatetime(new Date());
            model.setUpdatetime(new Date());
            int result = shopCartMapper.insertSelective(model);
            if (result > 0) {
                return model.getId();
            }
        } catch (Exception e) {
            this.logger.error("createOne 异常", e);
        }
        return 0L;
    }

    @Override
    public boolean updateNum(Long id, Integer num, Long memberId) {
        boolean isSuccess = false;
        try {
            ShopCart model = new ShopCart();
            model.setId(id);
            model.setNum(num);
            model.setUpdatetime(new Date());
            Example example = new Example(ShopCart.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id", id);
            criteria.andEqualTo("memberid", memberId);
            int result = shopCartMapper.updateByExampleSelective(model, example);
            if (result > 0) {
                isSuccess = true;
            }
        } catch (Exception ex) {
            this.logger.error("updateNum 异常", ex);
        }

        return isSuccess;
    }

    @Override
    public boolean deleteOne(Long id, Long memberId) {
        boolean result = false;
        try {
            if (id > 0 && memberId > 0) {
                Example example = new Example(ShopCart.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("id", id);
                criteria.andEqualTo("memberid", memberId);
                result = this.shopCartMapper.deleteByExample(example) > 0;
            }
        } catch (Exception e) {
            this.logger.error("deleteOne 异常", e);

        }
        return result;

    }

    @Override
    public boolean deleteBatch(List<Long> ids, Long memberId) {
        boolean result = false;
        try {
            if (ids.size() > 0 && memberId > 0) {
                Example example = new Example(ShopCart.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIn("id", ids);
                criteria.andEqualTo("memberid", memberId);
                result = this.shopCartMapper.deleteByExample(example) > 0;
            }
        } catch (Exception e) {
            this.logger.error("deleteOne 异常", e);

        }
        return result;
    }

    @Override
    public MsgDatasVO getList(Long memberId, Long areaId) {
        MsgDatasVO result = new MsgDatasVO();
        try {

            StringBuffer sb = new StringBuffer();
            sb.append("SELECT s.id,s.title,s.image,s.num,s.price oldprice,i.`status`,i.price nowprice" +
                    ", promitem.price promprice" +
                    ",(select sum(num) from t_item_store where itemid = s.itemid AND areaid = "+areaId+") storenum"+
                    ",promitem.pronum from t_shopcart s INNER JOIN t_item i on s.itemid=i.id " +
                    " LEFT JOIN (select i.itemid,i.price,i.num pronum from t_promotion p,t_promotion_item i " +
                    " where p.id=i.promid and i.num>0 and  (NOW() BETWEEN p.starttime AND p.endtime)) promitem" +
                    " ON i.id=promitem.itemid" +
                   // " LEFT JOIN t_item_store t ON t.itemid=s.itemid  AND t.areaid =" + areaId + "" +
                    " where s.memberid=" + memberId + "  ORDER BY s.id DESC");

            List<Map<String, Object>> dataList = customMapper.select(sb.toString());
            if (dataList != null && dataList.size() > 0) {
                dataList.forEach(map -> {
                    BigDecimal price = new BigDecimal(0);
                    Object nowpice = map.get("nowprice");
                    Object promprice = map.get("promprice");
                    Integer buyNum = Integer.valueOf(map.get("num").toString());
                    Integer promNum = 0;
                    Integer storeNum = 0;
                    if (map.get("pronum") != null) {
                        promNum = Integer.valueOf(map.get("pronum").toString());
                    }
                    if (map.get("storenum") != null) {
                        storeNum = Integer.valueOf(map.get("storenum").toString());
                    }
                    price = new BigDecimal(nowpice.toString()); //默认是商品原价
                    if (promprice != null && nowpice != null) {
                        //如果是促销商品，则价格为低的那个价格
                        BigDecimal tempPromPrice = new BigDecimal(promprice.toString());
                        BigDecimal tempNowPrice = new BigDecimal(nowpice.toString());
                        if (tempPromPrice.compareTo(tempNowPrice) >= 0) {
                            price = tempNowPrice;
                        } else {
                            price = tempPromPrice;
                        }
                    }
                    Integer status = 0;
                    if (promNum > 0) {
                        if (promNum >= buyNum) {
                            status = 1;
                        }
                    } else {
                        if (storeNum >= buyNum) {
                            status = 1;
                        }
                    }
                    map.put("status", status);
                    map.put("price", price);
                    map.put("origprice",nowpice);
                    //移除这几个属性
                    map.remove("nowprice");
                    map.remove("promprice");
                    map.remove("pronum");
                    map.remove("storenum");
                });
            }
            result.setDatas(dataList);
            result.setTotal(dataList.size());
        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;

    }

    @Override
    public ShopCart getOne(Long itemId, Long memberId) {
        Example example = new Example(ShopCart.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemid", itemId);
        criteria.andEqualTo("memberid", memberId);
        List<ShopCart> shopCarts = this.shopCartMapper.selectByExample(example);
        if (shopCarts != null && shopCarts.size() > 0) {
            return shopCarts.get(0);
        }
        return null;
    }

    @Override
    public MsgDatasVO getListByIds(List<Long> ids, Long memberId, Long areaId) {
        MsgDatasVO result = new MsgDatasVO();
        try {
            //将List<long>转为List<String>
            List<String> stringIds=ids.stream().map(s -> (s.toString())).collect(Collectors.toList());

            StringBuffer sb = new StringBuffer();
            sb.append("SELECT s.itemid,s.id,s.title,s.image,s.num,s.price oldprice,i.`status`,i.price nowprice" +
                    ", promitem.price promprice" +
                    ",(select sum(num) from t_item_store where itemid = s.itemid AND areaid = "+areaId+") storenum"+
                    ",promitem.pronum,promitem.promid from t_shopcart s INNER JOIN t_item i on s.itemid=i.id " +
                    " LEFT JOIN (select i.itemid,i.price,i.num pronum,i.promid from t_promotion p,t_promotion_item i " +
                    " where p.id=i.promid and i.num>0 and  (NOW() BETWEEN p.starttime AND p.endtime)) promitem" +
                    " ON i.id=promitem.itemid" +
                    //" LEFT JOIN t_item_store t ON t.itemid=s.itemid  AND t.areaid =" + areaId + "" +
                    " where s.memberid=" + memberId + "  and s.id in("+String.join(",", stringIds)+")  ORDER BY s.id DESC");

            List<Map<String, Object>> dataList = customMapper.select(sb.toString());
            if (dataList != null && dataList.size() > 0) {
                dataList.forEach(map -> {
                    BigDecimal price = new BigDecimal(0);
                    Object nowpice = map.get("nowprice");
                    Object promprice = map.get("promprice");
                    Integer buyNum = Integer.valueOf(map.get("num").toString());
                    Integer promNum = 0;
                    Integer storeNum = 0;
                    if (map.get("pronum") != null) {
                        promNum = Integer.valueOf(map.get("pronum").toString());
                    }
                    if (map.get("storenum") != null) {
                        storeNum = Integer.valueOf(map.get("storenum").toString());
                    }
                    price = new BigDecimal(nowpice.toString()); //默认是商品原价
                    if (promprice != null && nowpice != null) {
                        //如果是促销商品，则价格为低的那个价格
                        BigDecimal tempPromPrice = new BigDecimal(promprice.toString());
                        BigDecimal tempNowPrice = new BigDecimal(promprice.toString());
                        if (tempPromPrice.compareTo(tempNowPrice) >= 0) {
                            price = tempNowPrice;
                        } else {
                            price = tempPromPrice;
                        }
                    }
                    Integer status = 0;
                    if (promNum > 0) {
                        if (promNum >= buyNum) {
                            status = 1;
                        }
                    } else {
                        if (storeNum >= buyNum) {
                            status = 1;
                        }
                    }
                    map.put("status", status);
                    map.put("price", price);
                    //移除这几个属性
                    map.remove("nowprice");
                    map.remove("promprice");
                    map.remove("pronum");
                    map.remove("storenum");
                });
            }
            result.setDatas(dataList);
            result.setTotal(dataList.size());
        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;
    }

    @Override
    public ShopCart getOneById(Long id) {
        return this.shopCartMapper.selectByPrimaryKey(id);
    }
}
